package com.cw.service.impl;

import com.cw.mapper.DeptMapper;
import com.cw.mapper.EmpMapper;
import com.cw.pojo.Dept;
import com.cw.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //Sping事务管理(出现所有异常均回滚事务)
    public void delete(Integer id) throws Exception {
        deptMapper.deleteById(id);  //根据ID删除部门数据

//        int i = 1 / 0; //模拟抛出异常
//        if (true) {
//            throw new Exception("出错了"); //出现RunTimeException才会自动回滚事务
//        }
        empMapper.deleteByDeptId(id); //根据部门ID删除该部门下的员工
    }

    @Override
    public void add(Dept dept) {
        //需补全创建时间和更新时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept select(Integer id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }


}
